<template>
  <eh />
  <div class="update-container">
    <div class="update-card">
      <div class="update-card-body">
        <div class="update-title-group">
          <h2 class="update-title">修改个人资料</h2>
        </div>

        <div class="md:flex">
          <div class="md:flex-shrink-0 p-6">
            <div class="relative w-48 h-48 mx-auto">
              <!-- 头像预览 -->
              <img v-if="form.avatarPreview || Avatar" :src="form.avatarPreview || Avatar"
                class="w-48 h-48 rounded-full object-cover border-4 border-orange-200 shadow-lg"
                alt="User avatar preview">
              <img v-else class="w-48 h-48 rounded-full object-cover border-4 border-orange-200 shadow-lg"
                src="../assets/images/catt.png" alt="Default User avatar">
              <!-- 上传按钮覆盖在头像上 -->
              <label for="avatar"
                class="absolute bottom-0 right-0 bg-orange-100 rounded-full p-2 shadow-lg cursor-pointer hover:bg-orange-200 transition-colors">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-orange-600" fill="none" viewBox="0 0 24 24"
                  stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                <input type="file" id="avatar" @change="onFileChange" class="hidden" accept="image/*">
              </label>
            </div>
          </div>

          <div class="p-8 w-full">
            <form @submit.prevent="updateProfile" class="space-y-6">
              <!-- 昵称 -->
              <div class="form-group">
                <label for="username" class="block text-lg font-semibold text-orange-800 mb-2">昵称</label>
                <div class="relative">
                  <input type="text" id="username" v-model="form.username" required
                    class="w-full px-4 py-3 pl-12 rounded-lg border border-orange-300 focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all duration-300 bg-orange-50">
                  <UserIcon class="absolute left-3 top-1/2 transform -translate-y-1/2 text-orange-400" size="20" />
                </div>
              </div>

              <!-- 当前密码 -->
              <div class="form-group">
                <label for="password" class="block text-lg font-semibold text-orange-800 mb-2">当前密码</label>
                <div class="relative">
                  <input type="password" id="password" v-model="form.password" required
                    class="w-full px-4 py-3 pl-12 rounded-lg border border-orange-300 focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all duration-300 bg-orange-50">
                  <LockIcon class="absolute left-3 top-1/2 transform -translate-y-1/2 text-orange-400" size="20" />
                </div>
                <span v-if="!isCurrentPasswordValid && form.password !== ''" class="text-red-500 text-sm mt-1 block">
                  密码错误
                </span>
              </div>

              <!-- 新密码 -->
              <div class="form-group">
                <label for="new-password" class="block text-lg font-semibold text-orange-800 mb-2">修改密码</label>
                <div class="relative">
                  <input type="password" id="new-password" v-model="form.newPassword"
                    class="w-full px-4 py-3 pl-12 rounded-lg border border-orange-300 focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all duration-300 bg-orange-50">
                  <LockIcon class="absolute left-3 top-1/2 transform -translate-y-1/2 text-orange-400" size="20" />
                </div>
              </div>

              <!-- 确认密码 -->
              <div class="form-group">
                <label for="confirm-password" class="block text-lg font-semibold text-orange-800 mb-2">确认密码</label>
                <div class="relative">
                  <input type="password" id="confirm-password" v-model="form.confirmPassword"
                    class="w-full px-4 py-3 pl-12 rounded-lg border border-orange-300 focus:ring-2 focus:ring-orange-500 focus:border-orange-500 transition-all duration-300 bg-orange-50">
                  <LockIcon class="absolute left-3 top-1/2 transform -translate-y-1/2 text-orange-400" size="20" />
                </div>
                <span v-if="!isPasswordsMatching && form.newPassword !== ''" class="text-red-500 text-sm mt-1 block">
                  密码不一致
                </span>
              </div>

              <!-- 按钮组 -->
              <div class="flex items-center justify-between pt-4">
                <button type="submit"
                  class="bg-gradient-to-r from-orange-600 to-orange-700 text-white px-8 py-3 rounded-full hover:from-orange-700 hover:to-orange-800 transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-orange-500 focus:ring-opacity-50 disabled:opacity-50 disabled:cursor-not-allowed"
                  :disabled="isSubmitting || !isCurrentPasswordValid || !isPasswordsMatching">
                  <span v-if="isSubmitting" class="flex items-center">
                    <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg"
                      fill="none" viewBox="0 0 24 24">
                      <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                      <path class="opacity-75" fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
                      </path>
                    </svg>
                    保存中...
                  </span>
                  <span v-else>保存修改</span>
                </button>
                <button type="button" @click="resetForm"
                  class="px-8 py-3 rounded-full border-2 border-orange-300 text-orange-600 hover:bg-orange-50 hover:border-orange-600 transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-orange-500 focus:ring-opacity-50">
                  重置
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
  <fonnter />
</template>

<script setup>
import axios from 'axios'
import { ref, reactive, onMounted, computed } from 'vue'
import fonnter from '../../components/fonnter.vue';
import eh from '../../components/esyhead.vue';
import Cookies from 'js-cookie';

const StoredPassword = ref('');

const initialForm = {
  username: '',
  password: '',
  newPassword: '',
  confirmPassword: '',
  avatar: null,
  avatarPreview: ''
};

const form = reactive({ ...initialForm });
const isSubmitting = ref(false);
const Avatar = ref('');
const accountName = ref('');
const Nickname = ref('');
const Password = ref('');

onMounted(() => {
  const storedUser = sessionStorage.getItem('user');
  if (storedUser) {
    const { account, avatar, nickname, password } = JSON.parse(storedUser);
    accountName.value = account;
    Avatar.value = avatar;
    Nickname.value = nickname;
    Password.value = password;
    StoredPassword.value = password;
    form.username = nickname;
  }
});

const updateProfile = async () => {
  isSubmitting.value = true;
  try {
    if (!isCurrentPasswordValid.value) {
      throw new Error('当前密码不正确');
    }
    if (!isPasswordsMatching.value) {
      throw new Error('新密码与确认密码不匹配');
    }
    const token = Cookies.get('token');
    if (!token) {
      throw new Error('请先登录');
    }

    // 1. 先处理头像上传（如果有）

    if (form.avatar) {
      
      const avatarFormData = new FormData();
      avatarFormData.append('picture', form.avatar); // 注意字段名可能是'file'而不是'avatar'

      try {
        const avatarResponse = await axios.post(
          'http://localhost:8080/Petrescue/users/updateAvatar',
          avatarFormData,
          {
            headers: {
              'Content-Type': 'multipart/form-data',
              'Authorization': `Bearer ${Cookies.get('token')}` // 添加token
            },
            withCredentials: true
          }
        );

        if (avatarResponse.data.code !== "200") {
          throw new Error(avatarResponse.data.message || '头像上传失败');
        }
        
        // 更新头像预览
        Avatar.value = avatarResponse.data.data?.avatar || form.avatarPreview;
      } catch (error) {
        console.error('头像上传错误详情:', error.response?.data || error.message);
        throw new Error(`头像上传失败: ${error.response?.data?.message || error.message}`);
      }
    }

    // 2. 更新用户信息 - 改为发送JSON格式数据
    const userData = {
      nickname: form.username,
      password: form.newPassword || StoredPassword.value,
      confirmPassword: form.confirmPassword
    };

    const response = await axios.post(
      'http://localhost:8080/Petrescue/users/updateuser',
      userData,
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        withCredentials: true
      }
    );

    if (response.status === 200) {
      sessionStorage.setItem('user', JSON.stringify({
        avatar: form.avatarPreview || Avatar.value,
        nickname: form.username,
        password: form.newPassword || StoredPassword.value
      }));
      resetForm();
      alert('个人信息更新成功');
    } else {
      throw new Error(response.data.message || '更新失败');
    }
  } catch (error) {
    console.error('完整错误:', error);
    alert(error.response?.data?.message || error.message || '请求失败');
  } finally {
    isSubmitting.value = false;
  }
};

const onFileChange = (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 确保 FileReader 在正确的作用域中
  const reader = new FileReader(); // 不要放在条件块或嵌套函数中创建
  
  // 先绑定事件处理程序
  reader.onload = (event) => {
    form.avatarPreview = event.target.result;
  };
  
  // 然后开始读取
  reader.readAsDataURL(file);
  form.avatar = file; // 这行可以放在前面或后面
};

const resetForm = () => {
  Object.assign(form, initialForm);
  form.username = Nickname.value;
  document.getElementById('avatar').value = '';
};

const isCurrentPasswordValid = computed(() => {
  return form.password === StoredPassword.value;
});

const isPasswordsMatching = computed(() => {
  return form.newPassword === '' || form.newPassword === form.confirmPassword;
});
</script>

<style scoped lang="less">
.update-container {
  position: relative;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
}

.update-card {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 800px;
  border-radius: 1rem;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 251, 240, 0.9);
  border: 1px solid rgba(234, 88, 12, 0.3);
  animation: fadeIn 0.5s ease-out;
}

.update-card-body {
  padding: 1rem;
}

.update-title-group {
  text-align: center;
  margin-bottom: 2rem;
  padding-top: 1rem;
}

.update-title {
  font-size: 1.875rem;
  font-weight: 700;
  color: #7c2d12;
}

.form-group {
  transition: all 0.3s ease;
}

.form-group:focus-within {
  transform: scale(1.01);
}

input {
  transition: all 0.3s ease;
  color: #7c2d12;
  box-shadow: inset 0 1px 3px rgba(251, 191, 36, 0.1);

  &:not(:placeholder-shown) {
    background-color: rgba(254, 243, 199, 0.7);
    border-color: #ea580c;
    box-shadow: inset 0 1px 3px rgba(251, 191, 36, 0.2),
      0 0 0 1px rgba(234, 88, 12, 0.1);
  }

  &:focus {
    outline: none;
    background-color: rgba(254, 243, 199, 0.9);
    border-color: #c2410c;
    box-shadow: 0 0 0 2px rgba(234, 88, 12, 0.3),
      inset 0 1px 3px rgba(251, 191, 36, 0.3);
  }

  &::placeholder {
    color: #d97706;
    opacity: 0.7;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>